package thread3;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class MyResource {
    private boolean FLAG = true; // 如果为true的时候，则默认生产和消费
    private final AtomicInteger atomicInteger = new AtomicInteger();

    BlockingQueue<String> blockingQueue;

    public MyResource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println(blockingQueue.getClass().getName());
    }

    public void myProd() {
        String data;
        boolean returnVal;
        while (FLAG) {
            data = String.valueOf(atomicInteger.incrementAndGet());
            try {
                returnVal = blockingQueue.offer(data, 2L, TimeUnit.SECONDS);
                if (returnVal) {
                    System.out.println(Thread.currentThread().getName() + "\t 插入队列" + data + "成功");
                } else {
                    System.out.println(Thread.currentThread().getName() + "\t 插入队列" + data + "失败");
                }

                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(Thread.currentThread().getName() + "\t 当前生产者停止生产，flag为false");
    }

    public void myCustomer() {
        String data;
        while (FLAG) {
            try {
                data = blockingQueue.poll(2L, TimeUnit.SECONDS);
                if (data == null || "".equalsIgnoreCase(data)) {
                    FLAG = false;
                    System.out.println(Thread.currentThread().getName() + "\t" + "超过2秒没有可以消费的物品，消费退出");
                    return;
                }

                System.out.println(Thread.currentThread().getName() + "\t" + data + "消费队列成功");

                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(Thread.currentThread().getName() + "\t 当前消费者停止消费，flag为false");
    }

    public void stop() {
        this.FLAG = false;
    }
}

public class BlockQueueDemo {
    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(10);
        MyResource myResource = new MyResource(blockingQueue);

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t生产线程开始启动");
            myResource.myProd();
        }, "prod").start();

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t消费线程开始启动");
            myResource.myCustomer();
        }, "customer").start();

        try {
            TimeUnit.SECONDS.sleep(5);
            System.out.println("5秒时间到，停止生产和消费");
            myResource.stop();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
